package com.cloud.mqtt.util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author: JohnCoding
 * @Description: String工具类
 * @date: 2020/3/31 9:21
 */
public class StringUtils {


    /**
     * 按逗号分隔返回String[]
     * @param target
     * @return
     */
    public static String[] split(String target){
        return target.split(",");
    }

    public static String join(Iterable<?> iterable, String separator) {
        return iterable == null ? null : join(iterable.iterator(), separator);
    }


    public static boolean endsWithIgnoreCase(CharSequence str, CharSequence suffix) {
        return endsWith(str, suffix, true);
    }

    private static boolean endsWith(CharSequence str, CharSequence suffix, boolean ignoreCase) {
        if (str != null && suffix != null) {
            if (suffix.length() > str.length()) {
                return false;
            } else {
                int strOffset = str.length() - suffix.length();
                return regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length());
            }
        } else {
            return str == null && suffix == null;
        }
    }

    private static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart, CharSequence substring, int start, int length) {
        if (cs instanceof String && substring instanceof String) {
            return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
        } else {
            int index1 = thisStart;
            int index2 = start;
            int tmpLen = length;
            int srcLen = cs.length() - thisStart;
            int otherLen = substring.length() - start;
            if (thisStart >= 0 && start >= 0 && length >= 0) {
                if (srcLen >= length && otherLen >= length) {
                    while (tmpLen-- > 0) {
                        char c1 = cs.charAt(index1++);
                        char c2 = substring.charAt(index2++);
                        if (c1 != c2) {
                            if (!ignoreCase) {
                                return false;
                            }

                            if (Character.toUpperCase(c1) != Character.toUpperCase(c2) && Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
                                return false;
                            }
                        }
                    }

                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
    }

    public static String join(Object[] array, String separator) {
        return array == null ? null : join(array, separator, 0, array.length);
    }


    public static String join(Object[] array, String separator, int startIndex, int endIndex) {
        if (array == null) {
            return null;
        } else {
            if (separator == null) {
                separator = "";
            }

            int noOfItems = endIndex - startIndex;
            if (noOfItems <= 0) {
                return "";
            } else {
                StringBuilder buf = new StringBuilder(noOfItems * 16);

                for (int i = startIndex; i < endIndex; ++i) {
                    if (i > startIndex) {
                        buf.append(separator);
                    }

                    if (array[i] != null) {
                        buf.append(array[i]);
                    }
                }

                return buf.toString();
            }
        }
    }

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isEmpty(Object cs) {
        if (cs == null) return true;
        return cs.toString().length() == 0;
    }

    public static String join(Iterator<?> iterator, String separator) {
        if (iterator == null) {
            return null;
        } else if (!iterator.hasNext()) {
            return "";
        } else {
            Object first = iterator.next();
            if (!iterator.hasNext()) {
                return Objects.toString(first, "");
            } else {
                StringBuilder buf = new StringBuilder(256);
                if (first != null) {
                    buf.append(first);
                }

                while (iterator.hasNext()) {
                    if (separator != null) {
                        buf.append(separator);
                    }

                    Object obj = iterator.next();
                    if (obj != null) {
                        buf.append(obj);
                    }
                }

                return buf.toString();
            }
        }
    }

    /**
     * 首字母大写
     *
     * @param letter
     * @return
     */
    public static String uppercaseFirstChar(String letter) {
        char[] chars = letter.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char) (chars[0] - 32);
        }
        return new String(chars);
    }

    /**
     * 是否可以转换为数字
     *
     * @param obj
     * @return
     */
    public static boolean isNumericZidai(Object obj) {
        String str = obj + "";
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 首字母大写
     *
     * @param letter
     * @return
     */
    public static String lowercaseFirstChar(String letter) {
        char[] chars = letter.toCharArray();
        if (chars[0] >= 'A' && chars[0] <= 'Z') {
            chars[0] = (char) (chars[0] + 32);
        }
        return new String(chars);
    }

    /**
     * 根据给定的正则表达式返回匹配到的字符串
     *
     * @param regex
     * @param content
     * @return
     */
    public static String getMatchStr(String regex, String content) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                return matcher.group(i);
            }
        }
        return null;
    }

    /**
     * 根据给定的正则表达式返回匹配到的字符串
     *
     * @param regex
     * @param content
     * @return
     */
    public static String getMatchStr(String regex, String content, int group) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                if (i == group) return matcher.group(i);
            }
        }
        return null;
    }

    /**
     * 根据给定的正则表达式返回匹配到的字符串
     *
     * @param regex
     * @param content
     * @return
     */
    public static List<String> getMatchStrList(String regex, String content) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                result.add(matcher.group(i));
            }
        }
        return result;
    }

    /**
     * 根据给定的正则表达式返回匹配到的字符串
     *
     * @param regex
     * @param content
     * @return
     */
    public static boolean match(String regex, String content) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 生成随机的字符串
     *
     * @return
     */
    //length用户要求产生字符串的长度
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 把字符串在前面拼接root.  创建存储组的时候用到
     *
     * @param before
     * @return
     */
    public static String addRoot(String before) {
        StringBuffer root = new StringBuffer("root.");
        StringBuffer after = new StringBuffer(before);
        root.append(after);
        return root.toString();
    }


    /**
     *  把字符串拼接到root.DeviceId上   创建时间序列用到
     * @param deviceId
     * @param before
     * @return
     */
    public static String addDeviceIdAndRoot(String deviceId, String before) {
        StringBuffer after = new StringBuffer("root." + deviceId + ".");
        return after.append(before).toString();
    }


    /**
     * 按.号分割取最后一截字符串
     *
     * @param value
     * @return
     */
    public static String getLastString(String value) {
        if (0 == value.length()) {
            return null;
        }
        String[] split = value.split("\\.");
        String s = split[split.length - 1];
        return s;
    }

    /**
     * 按.号分割取最前面一截字符串
     *
     * @param value
     * @return
     */
    public static String getStartString(String value) {
        if (0 == value.length()) {
            return null;
        }
        String[] split = value.split("\\.");
        if(0 == split.length){
            return null;
        }
        return split[0];
    }


    /**
     * 在deviceId前面加d_  用于插入IOTDB数据库
     * @param deviceId
     * @return
     */
    public static String addDToDeviceId(String deviceId){
        return new StringBuffer("d_"+deviceId).toString();
    }


    /**
     * 判斷字符串是否為浮點型
     * @param str
     * @return
     */
    public static boolean isNumber(String str){
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    /**
     * String字符串转成List<String>数据格式
     * String str = "a,b,c,d,e,f" -> List<String> listString ['a','b','c','d','e','f'];
     *
     * @param strArr
     * @return
     */
    public static List<String> stringToStringList(String strArr) {
        return Arrays.stream(strArr.split(","))
                .map(s -> s.trim().toString())
                .collect(Collectors.toList());
    }

}
